package com.flyshop.module.admin.service;

import com.flyshop.common.utils.AdminSessionUtil;
import com.flyshop.common.utils.BCryptUtil;
import com.flyshop.common.utils.IpUtils;
import com.flyshop.core.entity.DataVo;
import com.flyshop.module.admin.dao.AdminDao;
import com.flyshop.module.admin.model.Admin;
import com.flyshop.module.webconfig.service.WebConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.Date;

@Service
public class AdminService {
    @Autowired
    private AdminDao dao;
    @Autowired
    private WebConfigService configService;
    /**
     * 用户注册基本信息
     *
     * @param admin_name
     *        用户注册登录名
     * @param password
     *        用户注册密码
     * @param request
     * @throws Exception
     */
    @Transactional
    public DataVo addUserReg(String admin_name, String password, HttpServletRequest request) throws Exception {
        Admin checkuser=this.findByUsername(admin_name);
        if (checkuser != null) {
            return DataVo.failure("该用户已存在，请换其他账户！");
        }
        Admin user = new Admin();
        user.setNickName(admin_name);
        user.setPassword(BCryptUtil.hashpw(password, BCryptUtil.gensalt()));
        user.setCreateAt(new Date());
        //添加用户账号和密码
        int userId = dao.addUser(user);
        //添加用户组权限
        dao.addUserAndRole(userId,Integer.parseInt(configService.getStringByKey("user_role")));
        Admin userinfo = dao.findUserById(userId,0);
        AdminSessionUtil.setLoginMember(request,userinfo);
        return DataVo.success("操作成功");
    }

    /**
     * 用户登陆
     *
     * @param username
     *        用户名
     * @param password
     *        密码
     * @param request
     * @throws Exception
     */
    public Admin userLogin(String username, String password, HttpServletRequest request) {

        Admin user = dao.findByUsername(username);
        if (user != null) {
            Admin login = new Admin();
            if (BCryptUtil.checkpw(password, user.getPassword())) {
                login.setId(user.getId());
                login.setAttempts(0);
                login.setLastLoginTime(new Date());
                login.setLastLoginIp(IpUtils.getIpAddr(request));
                dao.updateAdminLogin(login);

                //用户信息写入session
                AdminSessionUtil.setLoginMember(request,user);
            }else{
                login.setId(user.getId());
                login.setAttempts(user.getAttempts()+1);
                login.setAttemptsTime(new Date());
                dao.updateAdminLogin(login);
                user = null;
            }
        }
        return user;
    }


    /**
     * 通过username查询用户信息
     *
     * @param admin_name
     * @return Admin
     */
    public Admin findByUsername(String admin_name) {
        return dao.findByUsername(admin_name);
    }
}
